<script setup>
import dayjs from 'dayjs';
import { useRequest } from '@/hooks/requestHooks.js';
import { usePickerOption } from '@/views/hooks';
import { useInsStatics, useInsPieChart, useTGDealPieChart, useTGTrendChart } from './hooks.js';
import { contractType } from '@/constants.js';
import { getType } from '@/api/index.js';
import CECharts from '@/components/chart/CECharts.vue';
import Calendar from './components/Calendar.vue';
import InfoList from './components/InfoList.vue';

const emit = defineEmits(['handleRadioChange']);
const type = ref('TG');
const handleRadioChange = val => emit('handleRadioChange', val);
const staticTGList = [
  // {
  //   title: '托管项目（个）',
  //   staticKey: 'projectNum',
  //   subTitle: '年度托管项目',
  //   subKey: 'projectYearNum',
  //   bg: '#eb4e09',
  // },
  {
    title: '托管机构数（家）',
    staticKey: 'institutionCount',
    subTitle: '年度新增托管机构',
    subKey: 'yearInstitutionCount',
    bg: '#0973eb',
  },
  {
    title: '目标机构数（家）',
    staticKey: 'targetInstitutionCount',
    subTitle: '',
    subKey: '',
    bg: '#de8a0b',
  },
  {
    title: '托管投资总额（元）',
    staticKey: 'agreementAmount',
    subTitle: '年度托管合同总额',
    subKey: 'yearAgreementAmount',
    bg: '#db0e0e',
  },
  {
    title: '总节能量（吨标煤）',
    staticKey: 'energyConservation',
    subTitle: '年度节能总量',
    subKey: 'yearEnergyConservation',
    bg: '#21a726',
  },
  {
    title: '累计减排量（吨二氧化碳）',
    staticKey: 'emissionReductions',
    subTitle: '年度累计减排量',
    subKey: 'yearEmissionReductions',
    bg: '#06adb9',
  },
  {
    title: '项目总收益（元）',
    staticKey: 'projectEarnings',
    subTitle: '年度项目收益',
    subKey: 'yearProjectEarnings',
    bg: '#db0e0e',
  },
];
const contractTypeList = ref([{ code: 'ALL', name: '全部' }, ...contractType]);

const rangeType = ref({
  d: {
    type: 'daterange',
    fmt: 'yyyy-MM-dd',
    default: [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().subtract(1, 'day').format('YYYY-MM-DD')],
    pickerOptions: usePickerOption('d'),
  },
  m: {
    type: 'monthrange',
    fmt: 'yyyy-MM',
    default: [dayjs().subtract(6, 'month').format('YYYY-MM'), dayjs().subtract(1, 'month').format('YYYY-MM')],
    pickerOptions: usePickerOption('m'),
  },
  y: { type: 'year', fmt: 'yyyy', default: [dayjs().subtract(2, 'year').format('YYYY'), dayjs().format('YYYY')] },
});

const [engTypes] = useRequest(getType, {
  defaultParams: [{ all: '1' }],
  onSuccess: res => {
    lineExtraOpts1.value.yAxis[0].name = `单位：${res?.[0]?.energyUnit ?? ''}`;
  },
});
const [staticData, sLoading] = useInsStatics({ projectType: 'TG' });
const [extraPieOpts, pieLoading] = useInsPieChart('TG');
const [dPieOpts, dPieLoading] = useTGDealPieChart();
const [
  queryParams1,
  loading1,
  lineExtraOpts1,
  dateRange1,
  yearRange1,
  handleBuildingCode1,
  handleDaterange1,
  handleYearrange1,
] = useTGTrendChart(rangeType);
const changeType = item => {
  lineExtraOpts1.value.yAxis[0].name = `单位：${item?.energyUnit ?? ''}`;
};
// 开始时间不能大于结束时间
const disabledDateStart1 = ref({
  disabledDate: time => {
    if (yearRange1.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRange1.value.eYear) || dayjs(time) < dayjs(yearRange1.value.eYear).subtract(2, 'year')
      );
    }
  },
});
const disabledDateStart2 = ref({
  disabledDate: time => {
    if (yearRange2.value.eYear) {
      return dayjs(time) > dayjs(yearRange2.value.eYear);
    }
  },
});
// 结束时间不能小于开始时间
const disabledDate1 = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRange1.value.sYear) || dayjs(time) > dayjs(yearRange1.value.sYear).add(2, 'year');
  },
});
const disabledDate2 = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRange2.value.sYear);
  },
});
</script>

<template>
  <div class="app-container">
    <div class="u-df-st u-mb20">
      <div class="u-mr20">
        <el-radio-group v-model="type" size="small" style="margin-bottom: 15px" @input="handleRadioChange">
          <el-radio-button label="JC">监测</el-radio-button>
          <el-radio-button label="TG">托管</el-radio-button>
        </el-radio-group>
        <div class="u-fs20 u-fw-b">欢迎回到能源管理服务系统</div>
      </div>
      <ul class="TGHome-staticList u-df-st">
        <li
          v-for="(item, idx) in staticTGList"
          :key="item.staticKey"
          :class="idx < staticTGList.length - 1 ? 'u-mr20' : null"
          :style="{ backgroundColor: item.bg }"
        >
          <div>
            <div class="u-mb5">{{ item.title }}</div>
            <div class="u-title20 u-fw-b u-fs20">
              <el-skeleton :loading="sLoading" :rows="1" animated>
                <template>
                  <span>{{ staticData?.[item.staticKey] ?? '--' }}</span>
                </template>
              </el-skeleton>
            </div>
          </div>
          <div class="TGHome-staticList-subItem u-title20 u-fs12" :style="{ color: item.bg }">
            <el-skeleton :loading="sLoading" :rows="1" animated>
              <template>
                <span>{{ item.subTitle }} {{ staticData?.[item.subKey] }}</span>
              </template>
            </el-skeleton>
          </div>
        </li>
      </ul>
    </div>
    <div class="u-df-st u-h100">
      <div class="EMHome-left">
        <div class="u-w100 u-df-st u-mb20 tg-pieBox">
          <div class="homeChart-subBox u-p20 u-base-fg u-mr20">
            <div class="u-title20 u-fs16 u-prim-text">托管机构行业分类占比</div>
            <CECharts v-loading="pieLoading" :options="extraPieOpts" type="pie" style="height: calc(100% - 20px)" />
          </div>
          <div class="homeChart-subBox u-p20 u-base-fg">
            <div class="u-title20 u-fs16 u-prim-text">托管机构合同类型分类占比</div>
            <CECharts v-loading="dPieLoading" :options="dPieOpts" type="pie" style="height: calc(100% - 20px)" />
          </div>
        </div>
        <div class="u-p20 u-base-fg tg-chartBox">
          <el-form :model="queryParams1" :inline="true" class="tg-chartBox-form">
            <el-form-item prop="contractType">
              <el-select
                v-model="queryParams1.contractType"
                placeholder=""
                size="mini"
                style="width: 200px"
                class="u-mr10"
                @change="handleBuildingCode1"
              >
                <el-option
                  v-for="item in contractTypeList ?? []"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="energyType" class="u-mr10">
              <el-select v-model="queryParams1.energyType" placeholder="" size="mini" class="u-mr10">
                <el-option
                  v-for="item in engTypes"
                  :key="item.id"
                  :label="item.energyName + '能耗'"
                  :value="item.id"
                  @click.native="changeType(item)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="rangeType[queryParams1.dateType].type !== 'year'">
              <el-date-picker
                v-model="dateRange1"
                :type="rangeType[queryParams1.dateType].type ?? 'daterange'"
                :key="rangeType[queryParams1.dateType].type ?? 'daterange'"
                :value-format="rangeType[queryParams1.dateType].fmt ?? 'yyyy-MM-dd'"
                :picker-options="rangeType[queryParams1.dateType].pickerOptions"
                :clearable="false"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
                align="left"
                class="u-mr10"
                style="width: 240px"
                @change="handleDaterange1"
              />
            </el-form-item>
            <el-form-item v-else>
              <el-date-picker
                v-model="yearRange1.sYear"
                :picker-options="disabledDateStart1"
                :clearable="false"
                type="year"
                value-format="yyyy"
                placeholder="开始年份"
                size="mini"
                style="width: 115px"
                class="u-mr5"
                @change="handleYearrange1"
              />
              <el-date-picker
                v-model="yearRange1.eYear"
                :picker-options="disabledDate1"
                :clearable="false"
                type="year"
                value-format="yyyy"
                placeholder="结束年份"
                size="mini"
                class="u-mr10"
                style="width: 115px"
                @change="handleYearrange1"
              />
            </el-form-item>
            <el-form-item prop="dateType">
              <el-radio-group v-model="queryParams1.dateType" size="mini">
                <el-radio-button label="d">日</el-radio-button>
                <el-radio-button label="m">月</el-radio-button>
                <el-radio-button label="y">年</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <CECharts v-loading="loading1" :options="lineExtraOpts1" type="line" />
        </div>
      </div>
      <div class="EMHome-right">
        <Calendar type="TG" class="home-calendar u-mb20" />
        <InfoList class="home-calendar" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.TGHome-staticList {
  flex: 1;
  > li {
    flex: 1;
    color: #f5f5f5;
    font-size: 14px;
    border-radius: 4px;
    > div:first-of-type {
      padding: 12px;
      padding-bottom: 5px;
    }
  }
  &-subItem {
    background-color: rgba(255, 255, 255, 0.8);
    padding: 0 12px;
    border-radius: 0 0 4px 4px;
  }
  :deep(.el-skeleton.is-animated .el-skeleton__item) {
    background: linear-gradient(
      90deg,
      rgba(242, 242, 242, 0.5) 25%,
      rgba(230, 230, 230, 0.5) 37%,
      rgba(242, 242, 242, 0.5) 63%
    );
  }
}
.tg-pieBox {
  height: calc(100% * 0.3);
}
.tg-chartBox {
  height: calc(100% * 0.7 - 20px);
  position: relative;
  &-form {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 999;
  }
}
:deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 0 !important;
}
:deep(.el-form-item__content) {
  height: 28px;
  line-height: 28px;
}
:deep(.el-radio-button__inner) {
  height: 28px !important;
}
:deep(.el-radio-button--mini .el-radio-button__inner) {
  padding: 7px;
}
</style>
